<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../bower_components/polymer/polymer-element.html">



<link rel="import" href="../bower_components/app-storage/app-localstorage/app-localstorage-document.html">
<link rel="import" href="../bower_components/app-layout/app-header/app-header.html">
<link rel="import" href="../bower_components/app-layout/app-toolbar/app-toolbar.html">
<link rel="import" href="../bower_components/app-route/app-location.html">
<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="../bower_components/app-route/app-route-converter.html">
<link rel="import" href="../bower_components/app-layout/app-scroll-effects/effects/waterfall.html">
<link rel="import" href="../bower_components/app-layout/app-drawer/app-drawer.html">

<link rel="import" href="../bower_components/iron-form/iron-form.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../bower_components/iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../bower_components/iron-selector/iron-selectable.html">
<link rel="import" href="../bower_components/iron-iconset-svg/iron-iconset-svg.html">
<link rel="import" href="../bower_components/iron-media-query/iron-media-query.html">
<link rel="import" href="../bower_components/iron-pages/iron-pages.html">
<link rel="import" href="../bower_components/iron-selector/iron-selector.html">
<link rel="import" href="../bower_components/iron-icon/iron-icon.html">
<link rel="import" href="../bower_components/iron-image/iron-image.html">


<link rel="import" href="../bower_components/paper-button/paper-button.html">
<link rel="import" href="../bower_components/paper-tabs/paper-tabs.html">
<link rel="import" href="../bower_components/paper-tabs/paper-tab.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<link rel="import" href="../bower_components/paper-item/paper-item-body.html">
<link rel="import" href="../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">
<link rel="import" href="../bower_components/paper-behaviors/paper-ripple-behavior.html">
<link rel="import" href="../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="../bower_components/paper-dialog-scrollable/paper-dialog-scrollable.html">
<link rel="import" href="../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../bower_components/paper-item/paper-icon-item.html">
<link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../bower_components/paper-spinner/paper-spinner-lite.html">

<link rel="import" href="../bower_components/plugin-element/plugin-element.html">
<link rel="import" href="../bower_components/plugin-element/plugin-content-view.html">
<link rel="import" href="../bower_components/plugin-element/plugin-xhr.html">
<link rel="import" href="../bower_components/plugin-element/plugin-message.html">
<link rel="import" href="../bower_components/plugin-element/plugin-payment.html">
<link rel="import" href="../bower_components/plugin-element/plugin-area-selector.html">
<link rel="import" href="../bower_components/plugin-element/plugin-scroll-box.html">
<link rel="import" href="../bower_components/plugin-element/plugin-module-view.html">
<link rel="import" href="../bower_components/plugin-element/plugin-app-view.html">
<link rel="import" href="../bower_components/plugin-element/plugin-title-view.html">
<link rel="import" href="../bower_components/plugin-element/plugin-location-view.html">
<link rel="import" href="../bower_components/plugin-element/plugin-websocket.html">


<link rel="import" href="shop-cart-data.html">
<link rel="import" href="shop-cart-modal.html">
<link rel="import" href="shop-snackbar.html">
<link rel="import" href="shop-tabs.html">
<link rel="import" href="shop-tab.html">
<link rel="import" href="shop-tabs-overlay.html">
<link rel="import" href="shop-common-styles.html">
<link rel="import" href="shop-form-styles.html">
<link rel="import" href="shop-select.html">
<link rel="import" href="shop-checkbox.html">
<link rel="import" href="shop-input.html">
<link rel="import" href="shop-network-warning.html">
<link rel="import" href="shop-404-warning.html">
<link rel="import" href="shop-cart-item.html">
<link rel="import" href="shop-list-item.html">
<link rel="import" href="shop-ripple-container.html">
<link rel="import" href="shop-category-data.html">
<link rel="import" href="shop-image.html">
<link rel="import" href="shop-icons.html">
<link rel="import" href="shop-button.html">
<!-- Since 'home' is the default route, eagerly load it. -->
<!--<link rel="lazy-import" href="shop-home.html">
<link rel="lazy-import" href="shop-my.html">
<link rel="lazy-import" href="shop-my-trades.html">
<link rel="lazy-import" href="shop-my-trade.html">
<link rel="lazy-import" href="shop-my-coupons.html">
<link rel="lazy-import" href="shop-find.html">
<link rel="lazy-import" href="shop-find-news.html">
<link rel="lazy-import" href="shop-find-coupon.html">
<link rel="lazy-import" href="shop-find-discount.html">
<link rel="lazy-import" href="shop-customer-service.html">
<link rel="lazy-import" href="shop-my-score.html">
<link rel="lazy-import" href="shop-plugin.html">-->
<dom-module id="shop-app">

    <template>

    <style>

      :host {
        display: block;
        position: relative;
        padding-top: 130px;
        padding-bottom: 64px;
        min-height: 100vh;
        --app-primary-color: #202020;
        --app-secondary-color: #757575;
        --app-accent-color: #172C50;
        --paper-button-ink-color: var(--app-accent-color);
        --paper-icon-button-ink-color: var(--app-accent-color);
        --paper-spinner-color: var(--app-accent-color);
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        color: var(--app-primary-color);
      }

      app-header {
        @apply --layout-fixed-top;
        z-index: 2;
        background-color: rgba(255, 255, 255, 0.95);
        --app-header-shadow: {
          box-shadow: inset 0px 5px 6px -3px rgba(0, 0, 0, 0.2);
          height: 10px;
          bottom: -10px;
        };
          border-bottom: #ddd solid 1px;
      }

      paper-icon-button {
        color: var(--app-primary-color);
      }
        div[main-title]{
            height: 100%;
            display: flex;
            justify-content:flex-end;
        }
        div[main-title] paper-listbox{
            display: flex;
            justify-content: space-around;
            height: 100%;
            width: 100%;
            padding: 0px;
            --paper-listbox-background-color:none;
            max-width: 500px;
        }
        div[main-title] paper-listbox a{
            font-size: 12px;
            color: var(--app-primary-color);
            text-decoration: none;
            /* required for IE 11, so this <a> can receive pointer events */
            display:flex;
              flex-direction: column;
              align-items: center;
            pointer-events: auto;
            flex: 1;
            justify-content: center;
            align-items: center;
            position: relative;
            font-size:10px;
        }
        div[main-title] paper-listbox a.iron-selected{
            color: green;
        }
      .left-bar-item {
        width: 40px;
      }

      .menu-btn {
        display: none;
      }

      .announcer {
        position: fixed;
        height: 0;
        overflow: hidden;
      }

      :host(:not([page=detail])) .back-btn {
        /*display: none;*/
      }

      [hidden] {
        display: none !important;
      }

      .cart-badge {
        position: absolute;
        top: 5px;
        right: 0;
        width: 20px;
        height: 20px;
        background-color: var(--app-accent-color);
        border-radius: 50%;
        color: white;
        font-size: 12px;
        font-weight: 500;
        pointer-events: none;
        @apply --layout-vertical;
        @apply --layout-center-center;
      }

      .drawer-list {
        margin: 0 20px;
      }

      .drawer-list a {
        display: block;
        padding: 0 16px;
        line-height: 40px;
        text-decoration: none;
        color: var(--app-secondary-color);
      }

      .drawer-list a.iron-selected {
        color: black;
        font-weight: bold;
      }

      shop-cart-modal {
        z-index: 2;
      }

      app-drawer {
        z-index: 3;
      }

      iron-pages {
        max-width: 1440px;
        margin: 0 auto;
      }

        #customerService{
            position: fixed;
            bottom: 10px;
            margin-top:-30px;
            right: 10px;
            display: flex;
            border-radius: 50%;
            justify-content: center;
            flex-direction: column;
            background-color: rgba(0,0,0,0.75);
            width: 50px;
            height: 50px;
            justify-content: center;
            align-items: center;
            color: #fff;
            text-decoration: none;
            font-size: 12px;
            z-index: 2;
        }
        #customerService.action{
            bottom:70px;
        }
      /* small screen */
      @media (max-width: 767px) {
        :host {
          padding-top: 64px;
        }

        .menu-btn {
          display: block;
        }

        :host([page=detail]) .menu-btn {
          /*display: none;*/
        }
      }
      *, :focus, :hover, :active {
        outline:0;
    }
        .provider{
            padding: 10px;
            background-color: #eee;
            color: #333;
            font-size: 12px;
            position: absolute;
            bottom: 0px;
            text-align: center;
            width: 100%;
            box-sizing: border-box;
            z-index: 0;
        }
        .provider a{
            color: #000;
        }
    </style>
    <plugin-websocket id="websocket" auto url="{{wsHost}}/websocket/p2p?plugin_{{_cookie('token')}}" on-message="_websocketMessage"></plugin-websocket>
    <plugin-xhr auto url="{{apiHost}}/account.get.current" response="{{account}}" on-success="_accountLoaded"></plugin-xhr>
    <paper-spinner-lite style="position: fixed;left: 50%;top: 50%;margin-left:-20px;margin-top:-20px;z-index: 99999" id="loading" alt="loading..." class="orange"></paper-spinner-lite>
    <plugin-xhr auto url="{{apiHost}}/app.get?app_id={{appId}}" response="{{appInfo}}" on-success="_appInfoLoaded"></plugin-xhr>
    <plugin-xhr id="xhr_getAppLaunchScene" url="{{apiHost}}/wx.app.launch.scene"></plugin-xhr>
    <plugin-xhr id="xhr_removeAppLaunchScene" url="{{apiHost}}/wx.app.launch.scene.remove"></plugin-xhr>
    <plugin-xhr id="xhr_promotion_onetoone_add" url="{{apiHost}}/promotion.onetoone.add"></plugin-xhr>
    <plugin-xhr id="xhr_open_page" url="[[apiHost]]/wx.app.call?name=openPage&asyn=true"></plugin-xhr>
    <plugin-xhr auto url="[[apiHost]]/product.category.list?app_id={{appId}}" response="{{categories}}" response-property="result"></plugin-xhr>
        
    <!--
      app-location and app-route elements provide the state of the URL for the app.
    -->
    <app-location id="appLocation" route="{{route}}" url-space-regex="^{{rootPath}}"></app-location>
    <app-route
        route="{{route}}"
        pattern="{{rootPath}}:page"
        data="{{routeData}}"
        tail="{{subroute}}"></app-route>
    <app-route-converter path="{{route.path}}" query-params="{{queryParams}}" route="{{route}}"></app-route-converter>
    <iron-media-query query="max-width: 767px" query-matches="{{smallScreen}}"></iron-media-query>

    <!--
      shop-category-data provides the list of categories.
    -->
<!--    <shop-category-data id="categoryData" categories="{{categories}}"></shop-category-data>-->
    <!--
      shop-cart-data maintains the state of the user's shopping cart (in localstorage) and
      calculates the total amount.
    -->
    
    <shop-cart-data
        id="cart"
        cart="{{cart}}"
        num-items="{{numItems}}"
        total="{{total}}"></shop-cart-data>

    <app-header role="navigation" id="header" effects="waterfall" condenses reveals>
      <app-toolbar>
        <div class="left-bar-item">
          <paper-icon-button
              class="menu-btn"
              icon="menu"
              on-click="_toggleDrawer"
              aria-label="Categories">
          </paper-icon-button>
        </div>
        <div main-title>
            <paper-listbox selected="{{tabSelected}}">
                <a href="{{rootPath}}" aria-label="SHOP Home"><iron-icon icon="home"></iron-icon><span>主页</span></a>
                <a href="{{rootPath}}find" aria-label="Find"><iron-icon icon="explore"></iron-icon><span>发现</span></a>
                <a href="{{rootPath}}my" aria-label="My"><iron-icon icon="account-box"></iron-icon><span>我的</span></a>
                <a href="{{rootPath}}cart" tabindex="-1">
                    <iron-icon icon="shopping-cart" aria-label$="Shopping cart: [[_computePluralizedQuantity(numItems)]]"></iron-icon>
                    <span>购物车</span>
                    <span class="cart-badge" aria-hidden="true" hidden$="[[!numItems]]">[[numItems]]</span>
                  </a>
            </paper-listbox> 
        </div>
      </app-toolbar>
    </app-header>

    <app-drawer opened="{{drawerOpened}}" swipe-open tabindex="0">
        <iron-selector role="navigation" class="drawer-list" selected="[[categoryName]]" attr-for-selected="name">
          <dom-repeat items="[[categories]]" as="category" initial-count="4">
            <template>
              <a name="[[category.name]]" href="{{rootPath}}product/[[category.id]]">[[category.name]]</a>
            </template>
        </dom-repeat>
        </iron-selector>
    </app-drawer>

    <iron-pages id="mainbody" role="main" selected="[[page]]" attr-for-selected="name" selected-attribute="visible" fallback-selection="404">
        <!-- home view -->
        <shop-home name="home" categories="[[categories]]" layout="[[layout]]"></shop-home>
        <!-- cart view -->
        <shop-cart name="cart" cart="[[cart]]" total="[[total]]"></shop-cart>
        <!-- checkout view -->
        <shop-checkout name="checkout" cart="[[cart]]" total="[[total]]" route="{{subroute}}" layout="[[layout]]"></shop-checkout>
        <shop-my-trade name="my-trade" route="{{subroute}}" layout="[[layout]]"></shop-my-trade>
        <shop-my-trade-detail name="my-trade-detail" route="{{subroute}}" layout="[[layout]]"></shop-my-trade-detail>
        <shop-my-coupons name="my-coupons" route="{{subroute}}" layout="[[layout]]"></shop-my-coupons>
        <shop-my name="my" route="{{subroute}}" layout="[[layout]]"></shop-my>
        <shop-find name="find" route="{{subroute}}" layout="[[layout]]"></shop-find>
        <shop-find-news name="find-news" route="{{subroute}}" layout="[[layout]]"></shop-find-news>
        <shop-find-coupon name="find-coupon" route="{{subroute}}" layout="[[layout]]"></shop-find-coupon>
        <shop-find-discount name="find-discount" route="{{subroute}}" layout="[[layout]]"></shop-find-discount>
        <shop-customer-service name="customer-service" route="{{subroute}}" layout="[[layout]]"></shop-customer-service>
        <shop-my-score name="my-score" route="{{subroute}}" layout="[[layout]]"></shop-my-score>
        <shop-plugin name="plugin" route="[[subroute]]" layout="[[layout]]"></shop-plugin>
        <shop-blog name="blog" route="[[subroute]]" layout="[[layout]]"></shop-blog>
        <shop-blog-detail name="blog-detail" route="[[subroute]]" layout="[[layout]]"></shop-blog-detail>
        <shop-product name="product" route="[[subroute]]" layout="[[layout]]"></shop-product>
        <shop-product-detail name="product-detail" route="[[subroute]]" layout="[[layout]]"></shop-product-detail>
        <shop-404-warning name="404" route="[[subroute]]" layout="[[layout]]"></shop-404-warning>
    </iron-pages>
    <a id="customerService" href="{{rootPath}}customer-service" aria-label="Customer Service">
        <iron-icon icon="perm-phone-msg"></iron-icon>
    </a>
    <!-- a11y announcer -->
    <div class="announcer" aria-live="assertive">[[_a11yLabel]]</div>
    <div class="provider">由爱普魔方提供服务，<a href="javascript:void(0)" on-click="_viewImage" url="https://cdn.image.b2wx.com/image/wjad.png">我要开店</a></div>
    </template>

    <script>
        var app;
        class ShopApp extends PluginElement {

            static get is() {
                return 'shop-app';
            }

            static get properties() {
                return {
                    page: {
                        type: String,
                        reflectToAttribute: true,
                        observer: '_pageChanged'
                    },

                    numItems: {
                        type: Number,
                        value: 0
                    },

                    apiHost: {
                        type: String,
                        value: "https://" + (window.location.hostname.indexOf("template.") == 0 ? "appcenter.b2wx.com" : window.location.hostname) + "/plugin/api"
                    },
                    httpHost: {
                        type: String,
                        value: function() {
                            return "https://" + (window.location.hostname.indexOf("template.") == 0 ? "appcenter.b2wx.com" : window.location.hostname);
                        }
                    },
                    wsHost: {
                        type: String,
                        value: function() {
                            return "wss://" + (window.location.hostname.indexOf("template.") == 0 ? "appcenter.b2wx.com" : window.location.hostname);
                        }
                    },
                    appId: String,
                    categories: Array,
                    loadingCount: {
                        type: Number,
                        value: 0
                    },
                    pluginNotifyListener: {
                        type: Object,
                        value: {}
                    },
                    singleItem: {
                        type: Object,
                        notify: true
                    },
                    layout: {
                        type: Object,
                        notify: true
                    },
                    tabSelected: {
                        type: String,
                        value: "0"
                    },
                    token: String,
                    rootPath:String
                }
            }

            static get observers() {
                return [
                    '_routePageChanged(routeData.page)'
                ]
            }

            constructor() {
                super();
                app = this;
                if(this._param("app_id")){
                    this.appId = this._param("app_id");
                    this._cookie("app_id",this.appId);
                }else{
                    this.appId = this._cookie("app_id");
                }
            }

            ready() {
                super.ready();
                app.token = this._cookie("token");
                let dom = this;
                this.removeAttribute('unresolved');
                this.addEventListener('add-cart-item', (e) => this._onAddCartItem(e));
                this.addEventListener('set-cart-item', (e) => this._onSetCartItem(e));
                this.addEventListener('clear-cart', (e) => this._onClearCart(e));
                this.addEventListener('change-section', (e) => this._onChangeSection(e));
                this.addEventListener('announce', (e) => this._onAnnounce(e));
                this.addEventListener('show-invalid-url-warning', (e) => this._onFallbackSelectionTriggered(e));
                this.pluginNotifyListener.notify = function(config) {
                    if (config.success) {
                        config.success.call(app, {
                            errMsg: "ok"
                        });
                    }
                }
                this.pluginNotifyListener.openTrade = function(config) {
                    app._page(this.rootPath+"my-trade-detail/" + config.tradeId);
                    config.success.call(app, {
                        errMsg: "ok"
                    });
                }
                this.pluginNotifyListener.openItem = function(config) {
                    app._page(this.rootPath+"product-detail/"+config.productId);
                    config.success.call(app, {
                        errMsg: "ok"
                    });
                }
                this.pluginNotifyListener.openFindCoupon = function(config) {
                    app._page(this.rootPath+"find-coupon");
                    config.success.call(app, {
                        errMsg: "ok"
                    });
                }
                this.pluginNotifyListener.openFindDiscount = function(config) {
                    app._page(this.rootPath+"find-discount");
                    config.success.call(app, {
                        errMsg: "ok"
                    });
                }
                this.pluginNotifyListener.gotoHome = function(config) {
                    app._page(this.rootPath);
                    config.success.call(app, {
                        errMsg: "ok"
                    });
                }
                let layout = this._cache("design.layout");
                if (layout) {
                    this.layout = JSON.parse(layout);
                }

                let startFlush = false;
                let startFlushEvent = 0;
                let start_y = 0;
                let current_y = 0;
                let timeoutId = 0;
                document.body.addEventListener("touchmove", function(event_mousemove) {
                    current_y = (event_mousemove.touches ? event_mousemove.touches[0] : event_mousemove).pageY - window.pageYOffset;
                    if (startFlush && window.pageYOffset <= 1) {
                        if (start_y == 0) {
                            start_y = current_y;
                        }
                        document.body.querySelector("#flush").style.height = (current_y - start_y) + "px";
                        if (current_y - start_y >= 65) {
                            if (!timeoutId) {
                                timeoutId = window.setTimeout(function() {
                                    document.body.querySelector(".loading").style.display = "block";
                                }, 500);
                            }
                        } else {
                            if (timeoutId) {
                                window.clearTimeout(timeoutId);
                                timeoutId = 0;
                            }
                            document.body.querySelector(".loading").style.display = "none";
                        }
                    } else {
                        document.body.querySelector("#flush").style.height = "0px";
                        document.body.querySelector(".loading").style.display = "none";
                    }
                });

                function stop(event_mousemove) {
                    startFlush = false;
                    window.clearTimeout(startFlushEvent);
                    start_y = 0;
                    current_y = 0;
                    if (document.body.querySelector(".loading").style.display == "block") {
                        let path = window.location.href.split(app.httpHost).join("");
                        window.localStorage.setItem("flush." + app.appId + ".path", path);
                        window.localStorage.setItem("flush." + app.appId + ".tabSelected", dom.tabSelected);
                        window.location.href = document.querySelector("base").href + "?app_id=" + app.appId + "&flush=" + new Date().getTime();
                    }
                    document.body.querySelector(".loading").style.display = "none";
                    document.body.querySelector("#flush").style.height = "0px";
                }
                document.body.addEventListener("touchend", stop);
                document.body.addEventListener("touchcancel", stop);
                document.body.addEventListener("touchstart", function(e) {
                    startFlushEvent = window.setTimeout(function() {
                        startFlush = true;
                    }, 100);
                });
                if (this._param("flush")) {
                    let path = window.localStorage.getItem("flush." + app.appId + ".path");
                    let tabSelected = window.localStorage.getItem("flush." + app.appId + ".tabSelected");
                    dom.tabSelected = tabSelected;
                    window.localStorage.removeItem("flush." + app.appId + ".path");
                    window.localStorage.removeItem("flush." + app.appId + ".tabSelected");
                    this._page(path);
                }
                document.addEventListener("tap", function() {
                    dom._cookie("token", app.token);
                });
                document.addEventListener("click", function() {
                    dom._cookie("token", app.token);
                });
                document.addEventListener("mousedown", function() {
                    dom._cookie("token", app.token);
                });
            }
            _accountLoaded(e) {
                this._cookie("account_id",this.account.result.id);
                let dom = this;
                let scene = this._param("scene");
                if (scene) {
                    scene = JSON.parse(decodeURIComponent(scene));
                    if ("openItem" == scene.action) {
                        app._page(this.rootPath+"product-detail/" +scene.productId);
                    }
                    if ("openTrade" == scene.action) {
                        app._page(this.rootPath+"my-trade-detail/" + scene.tradeId);
                    }
                    if ("openShareItem" == scene.action) {
                        app._page(this.rootPath+"product-detail/" + scene.productId);
                    }
                }
            }
            _websocketMessage(e) {
                let dom = this;
                let data = e.detail;
                if (data == "heartbeat") {
                    return;
                }
                let to = "plugin_" + dom._cookie("token");
                let type = data.type;
                let apiNmae = data.name;
                let config = data.config;
                let callbacks = data.callbacks;
                if (typeof(data) == "object") {
                    if (data.type == "api") {
                        if (app.pluginNotifyListener[data.name]) {
                            if (callbacks) {
                                for (let callback in callbacks) {
                                    let callbackFun = callbacks[callback];
                                    config[callback] = function(res) {
                                        app.$.websocket.send(JSON.stringify({
                                            to: to,
                                            data: {
                                                result: res,
                                                callback: callbackFun
                                            }
                                        }));
                                    }
                                }
                            }
                            app.pluginNotifyListener[data.name].call(app, config);
                        } else {
                            app.$.websocket.send(JSON.stringify({
                                to: to,
                                data: {
                                    result: {
                                        errMsg: "接口不存在"
                                    },
                                    callback: "fail"
                                }
                            }));
                        }
                    }
                }
            }
            _reload() {
                let uri = window.location.href.split(this.httpHost).join("");
                uri = uri + (uri.indexOf("?") == -1 ? "?" : "&") + "r=" + new Date().getTime();
                this._page(uri);
            }
            _routePageChanged(page) {
                this.page = (page && page != "templategoods.pl" ? page : 'home');

                // Close the drawer - in case the *route* change came from a link in the drawer.
                this.drawerOpened = false;
                this.dispatchEvent(new CustomEvent("route-page-changed", {
                    detail: {
                        page: page
                    }
                }));

            }
            _pageChanged(page, oldPage) {
                wx.miniProgram.postMessage({
                    data: {
                        pageURL: window.location.href
                    }
                });
                if (page != null) {
                    app._openLoading();
                    let cb = this._pageLoaded.bind(this, Boolean(oldPage));
                    Polymer.importHref(this.resolveUrl('shop-' + page + '.html'), cb, cb, true);
                    this.dispatchEvent(new CustomEvent("page-changed", {
                        detail: {
                            page: page,
                            oldPage: oldPage
                        }
                    }));
                    Polymer.AppLayout.scroll({
                        top: 0,
                        behavior: 'silent'
                    });
                }
            }
            _pageLoaded(shouldResetLayout) {
                this._ensureLazyLoaded();
                if (shouldResetLayout) {
                    Polymer.Async.timeOut.run(() => {
                        this.$.header.resetLayout();
                    }, 1);
                }
                app._closeLoading();
                
            }
            _ensureLazyLoaded() {
                // load lazy resources after render and set `loadComplete` when done.
                if (!this.loadComplete) {
                    Polymer.RenderStatus.afterNextRender(this, () => {
                        Polymer.importHref(this.resolveUrl('lazy-resources.html'), () => {
                            // Register service worker if supported.
                            if ('serviceWorker' in navigator) {
                                navigator.serviceWorker.register('service-worker.js', {
                                    scope: '/templategoods.pl/'
                                });
                            }
                            this.loadComplete = true;
                        });
                    });
                }
            }

            _toggleDrawer() {
                this.drawerOpened = !this.drawerOpened;
            }

            // Elements in the app can notify section changes.
            // Response by a11y announcing the section and syncronizing the category.
            _onChangeSection(event) {
                let detail = event.detail;
                this.categoryName = detail.category || '';
                // Announce the page's title
                if (detail.title) {
                    //document.title = detail.title + ' - '+this.appInfo.result.app_name;
                    this._announce(detail.title + ', 已加载');
                }
            }

            _onAddCartItem(event) {
                if (!this._cartModal) {
                    this._cartModal = document.createElement('shop-cart-modal');
                    this.root.appendChild(this._cartModal);
                }
                this.$.cart.addItem(event.detail);
                this._cartModal.open();
                this._announce('商品已添加到购物车');
            }

            _onSetCartItem(event) {
                let detail = event.detail;
                this.$.cart.setItem(detail);
                if (detail.quantity === 0) {
                    this._announce('商品已从购物车中移除');
                } else {
                    this._announce('购物车商品数量已改变为' + detail.quantity);
                }
            }

            _onClearCart() {
                this.$.cart.clearCart();
                this._announce('购物车已清空');
            }

            // Elements in the app can notify a change to be a11y announced.
            _onAnnounce(e) {
                this._announce(e.detail);
            }

            // A11y announce the given message.
            _announce(message) {
                this._a11yLabel = '';
                this._announceDebouncer = Polymer.Debouncer.debounce(this._announceDebouncer,
                    Polymer.Async.timeOut.after(100), () => {
                        this._a11yLabel = message;
                    });
            }

            _onFallbackSelectionTriggered() {
                this.page = '404';
            }


            _computePluralizedQuantity(quantity) {
                return quantity + ' ' + (quantity === 1 ? 'item' : 'items');
            }
            navToPage(value) {
                let url = null;
                if (typeof(value) == "string") {
                    url = value;
                } else {
                    url = value.currentTarget.href;
                    if (!url) {
                        url = value.currentTarget.getAttribute("href");
                    }
                }
                let path = null;
                let params = new Object();
                if (url.indexOf("?") != -1) {
                    path = url.split("?")[0];
                    let query = url.split("?")[1];
                    query = query.split("&amp;").join("&");
                    let queryParams = query.split("&");
                    for (let i = 0; i < queryParams.length; i++) {
                        let queryParam = queryParams[i];
                        if (queryParam.indexOf("=") != -1) {
                            params[queryParam.substring(0, queryParam.indexOf("="))] = queryParam.substring(queryParam.indexOf("=") + 1, queryParam.length);
                        } else {
                            params[queryParam] = "";
                        }
                    }
                } else {
                    path = url;
                }
                app.queryParams = params;
                app.route = {
                    path: path,
                    prefix: ""
                };

            }
            _appInfoLoaded(e) {
                document.title = this.appInfo.result.app_name;
            }
            _openLoading() {
                this.loadingCount++;
                this.$.loading.active = true;
            }
            _closeLoading() {
                this.loadingCount--;
                if (this.loadingCount == 0) {
                    this.$.loading.active = false;
                }
            }
        }

        customElements.define(ShopApp.is, ShopApp);

    </script>

</dom-module>
